<template>

  <!-- <LoadingCmp :loading="loadingCmp" v-if="loadingCmp" /> -->

  <van-config-provider :theme-vars="themeVars">
    <van-dropdown-menu class="cinemas-dropdown" ref="districtDropdown">

      <van-dropdown-item :title="dropdownDistrictTitle" v-model="regionIndex" @change="changeDropdown">
        <van-tabs @click-tab="onClickTab" v-model:active="tabActive">

          <van-tab title="商区">


            <van-tree-select v-model:main-active-index="districtIndex" v-model:active-id="areaId"
              @click-nav="distHandleClickNav" @click-item="distHandleClickItem" :items="districtItems">

            </van-tree-select>

          </van-tab>

          <van-tab title="地铁站">
            <van-tree-select v-model:main-active-index="lineIndex" v-model:active-id="stationId"
              @click-nav="subHandleClickNav" @click-item="subHandleClickItem" :items="subwayItems">
            </van-tree-select>
          </van-tab>
        </van-tabs>
      </van-dropdown-item>
      <!--区域 -->
      <van-dropdown-item :title="dropdownBrandTitle" v-model="brandId" @change="changeBrand" :options="brandOption">
      </van-dropdown-item>
      <!--品牌 -->

      <van-dropdown-item :title="dropdownSpecialTitle" v-model="serviceId">
        <div class="special">
          <h5>{{ service.name }}</h5>
          <van-grid :border="false" :clickable="true" gutter="5">
            <van-grid-item v-for="item in service.subItems" :key="item.id" @click="handleServiceClick(item)">
              <van-button plain hairline block size="normal" class="special-btn"
                :class="{ 'active-btn': serviceId === item.id }">{{ item.name }}</van-button>
            </van-grid-item>
          </van-grid>

          <h5 style="margin-top: 10px">{{ hallType.name }}</h5>
          <van-grid :border="false" :clickable="true" :gutter="5">
            <van-grid-item v-for="item in hallType.subItems" :key="item.id" @click="handleHallTypeClick(item)">
              <van-button plain hairline block size="normal" class="special-btn"
                :class="{ 'active-btn': hallTypeId === item.id }">{{ item.name }}</van-button>
            </van-grid-item>
          </van-grid>

          <van-divider />

          <van-row justify="space-between" align="center">
            <van-col>
              <van-button plain hairline block size="normal" type="default" class="reset"
                @click="onReset">重置</van-button>
            </van-col>
            <van-col>
              <van-button plain hairline block size="normal" type="default" color="#e54847" class="confirm"
                @click="onConfirm">确定</van-button>
            </van-col>
          </van-row>
        </div>
      </van-dropdown-item>
      <!--特色 -->
    </van-dropdown-menu>

    <!-- 影院列表 -->
    <van-list class="list" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <ul>
        <li v-for="cinema in cinemas" :key="cinema.cinemaId" class="cinema-item"
          @click="goToCinemaDetail(cinema.cinemaId)">
          <van-row class="title">
            <van-col class="line-width line-ellipsis">{{ cinema.title }}</van-col>
            <van-col class="price">{{ cinema.price.n }} <span>{{ cinema.price.q }}</span></van-col>
          </van-row>
          <van-row class="location">
            <van-col class="line-ellipsis line-width">{{ cinema.location }}</van-col>
          </van-row>
          <van-row class="services">
            <van-col v-for="(item, index) in cinema.services" :key="index"><van-tag plain type="primary">{{ item.text
                }}</van-tag></van-col>
          </van-row>
        </li>
      </ul>
    </van-list>
  </van-config-provider>
</template>

<script setup>


import { fetchCinemas, fetchCinemasList } from '@/api/index.js'

import { ref, onMounted, computed, watch, reactive } from 'vue'

import { useRouter } from 'vue-router'
const router = useRouter()

// const loadingCmp = ref(true)

const themeVars = reactive({
  gridItemContentPadding: '0px',
  buttonDefaultColor: '#777',
})

import { useStore } from '@/stores/index.js'
const store = useStore()

const loading = ref(false)
const finished = ref(false)
const tabActive = ref(0)

const district = ref({})
const brand = ref({})
const service = ref({})
const hallType = ref({})
const subway = ref({})

const dropdownDistrictTitle = ref('全城') // 初始标题
const dropdownBrandTitle = ref('品牌') // 初始标题

const serviceTitle = ref('全部')
const hallTypeTitle = ref('全部')

const dropdownSpecialTitle = computed(() => {
  const service = serviceTitle.value;
  const hallType = hallTypeTitle.value;

  if (service === '全部' && hallType === '全部') {
    return '特色';
  }
  if (service === '全部' && hallType != '全部') {
    return hallType;
  }
  if (hallType === '全部' && service != '全部') {
    return service;
  }
  return `${service},${hallType}`;
});


const regionIndex = ref(0) //  行政区 or 地铁

const districtIndex = ref(0) //  行政区 索引

const districtId = ref(-1) //行政区
const areaId = ref(-1)     //商区

const lineIndex = ref(0) //  地铁 索引

const lineId = ref(-1) // 地铁线路 默认全部
const stationId = ref(-1) //  地铁站点 默认全部


const brandId = ref(-1)
const serviceId = ref(-1)

const hallTypeId = ref(-1)


const cinemas = ref([])
const pageNum = ref(1)
const limit = ref(20)

const offset = computed(() => {
  return (pageNum.value - 1) * limit.value
})

// 获取 van-dropdown-item 的实例
const districtDropdown = ref(null)

const districtItems = ref([])
const subwayItems = ref([])
const brandOption = ref([])
// const specialOption = ref([])

// 商圈数据转换
function transformDistrictData (district) {
  return district.subItems.map((item, index) => {
    // console.log('item:', item); // 打印每个元素，检查是否有异常
    return {
      index: index, // 行政区 索引
      id: item.id, //行政区ID
      text: item.name + '(' + item.count + ')',  //行政区名称 + 数量
      count: item.count,
      children: item.subItems.map((subItem) => {
        return {
          text: subItem.name + '(' + subItem.count + ')',  //商圈名 + 数量
          id: subItem.id,        // 商区实际的ID
          count: subItem.count,
        }
      }),
    }
  })
}

//地铁数据转化
function transformSubwayData (subway) {
  return subway.subItems.map((item, index) => {
    return {
      index: index, //地铁 索引
      id: item.id, //地铁线路 ID  lineId
      text: item.name, // 地铁线路名称
      count: item.count,
      children: item.subItems.map((subItem) => {
        return {
          text: subItem.name, // 地铁 站点名称
          id: subItem.id, // 地铁 站点ID
          count: subItem.count,
        }
      }),
    }
  })
}

const changeDropdown = (value) => {
  // console.log("changeDropdown", value);
  // console.log("regionIndex", regionIndex.value);

}

// 电影院筛选条件
const getCinemaListFilters = async () => {
  // 电影院筛选条件
  const res = await fetchCinemas(store.currentCity.id)
  brand.value = res.brand
  district.value = res.district
  hallType.value = res.hallType
  service.value = res.service
  subway.value = res.subway

  // 行政区商圈数据填充
  districtItems.value = transformDistrictData(district.value)

  console.log("districtItems", districtItems.value);


  // 地铁数据填充
  subwayItems.value = transformSubwayData(subway.value)

  // console.log("subwayItems", subwayItems.value);


  //填充品牌
  brand.value.subItems.forEach((item) => {
    brandOption.value.push({ text: item.name, count: item.count, value: item.id, id: item.id })
  })

}

// 根据筛选结果查询电影院列表
const getCinemaListByFilters = async (offset, limit, districtId, areaId, lineId, stationId, boolean, hallTypeId, brandId, serviceId, cityId, latitude, longitude) => {
  loading.value = true
  const response = await fetchCinemasList(
    offset,
    limit,
    districtId,
    areaId,
    lineId,
    stationId,
    boolean,
    hallTypeId,
    brandId,
    serviceId,
    cityId,
    latitude,
    longitude,
  )
  loading.value = false
  if (response.length === 0) {
    finished.value = true
    // showToast({ message: '没有更多了' })
    return
  } else {
    cinemas.value.push(...response)

    console.log("cinemas.value", cinemas.value)
    store.setCinemas(cinemas.value) //当前城市全部电影院

  }

}




onMounted(async () => {
  // loadingCmp.value = true
  // console.log('CinemaCmp  onMounted')

  await getCinemaListFilters()

  //默认加载全部电影院列表
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, lineId.value, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)

  // distHandleClickNav(0)

})

const onLoad = async () => {
  // 加载更多电影院列表
  pageNum.value = pageNum.value + 1 // 页码加1，尝试加载更多
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, lineId.value, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)

}

// 监听行政区变化
watch(districtId, async (newdistrictId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  if (newdistrictId === -1) {
    areaId.value = -1
  }
  await getCinemaListByFilters(offset.value, limit.value, newdistrictId, areaId.value, lineId.value, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
})

// 监听商圈变化
watch(areaId, async (newAreaId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, newAreaId, lineId.value, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
})

// 监听地铁线路变化
watch(lineId, async (newlineId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  if (newlineId === -1) {
    stationId.value = -1
  }
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, newlineId, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
})

// 监听地铁站点变化
watch(stationId, async (newstationId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, lineId.value, newstationId, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
})


//监听品牌变化
watch(brandId, async (newbrandId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, lineId.value, stationId.value, true, hallTypeId.value, newbrandId, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
})

const onClickTab = ({ name }) => {
  // console.log("onClickTab", name);
}

const changeBrand = (value) => {

  brandId.value = value
  dropdownBrandTitle.value = brandOption.value.find((item) => item.id === value).text
}

// 商区一级筛选 行政区
const distHandleClickNav = (index) => {
  districtId.value = districtItems.value[index].id // 点击的行政区ID
  // 更新 dropdown-item 的标题
  if (districtItems.value[index].id !== -1) {
    dropdownDistrictTitle.value = districtItems.value[index].text
  } else {
    dropdownDistrictTitle.value = '全城'
  }
  // 关闭下拉菜单
  if (index === 0) {
    districtDropdown.value.close()
  }
}
// 商区二级筛选  商圈
const distHandleClickItem = (item) => {
  areaId.value = item.id //点击的商圈ID
  // 更新 dropdown-item 的标题
  if (item.id !== -1) {
    dropdownDistrictTitle.value = item.text
  } else {
    dropdownDistrictTitle.value = districtItems.value[districtIndex.value].text
  }
  // 关闭下拉菜单
  districtDropdown.value.close()
}


// 地铁一级筛选  地铁几号线？
const subHandleClickNav = (index) => {
  lineId.value = subwayItems.value[index].id // 点击的行政区ID

  // console.log("lineId", lineId.value);
  // 更新 dropdown-item 的标题
  if (subwayItems.value[index].id !== -1) {
    dropdownDistrictTitle.value = subwayItems.value[index].text
  } else {
    dropdownDistrictTitle.value = '全城'
  }
  // 关闭下拉菜单
  if (index === 0) {
    districtDropdown.value.close()
  }
}

// 地铁二级筛选  地铁站?
const subHandleClickItem = (item) => {
  stationId.value = item.id //点击的商圈ID

  // console.log("stationId", stationId.value);
  // 更新 dropdown-item 的标题
  if (item.id !== -1) {
    dropdownDistrictTitle.value = item.text
  } else {
    dropdownDistrictTitle.value = subwayItems.value[lineIndex.value].text
  }
  // 关闭下拉菜单
  districtDropdown.value.close()
}

// 特色 影院服务
const handleServiceClick = (item) => {
  serviceId.value = item.id
  serviceTitle.value = item.name
}

//特色 影厅类型
const handleHallTypeClick = (item) => {
  // console.log('handleHallTypeClick', item)
  hallTypeId.value = item.id
  hallTypeTitle.value = item.name
}

// 重置
const onReset = () => {
  serviceId.value = -1
  hallTypeId.value = -1

  serviceTitle.value = '全部';
  hallTypeTitle.value = '全部';
}

// 确定
const onConfirm = async () => {
  //关闭dropdown-menu
  districtDropdown.value.close()

  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getCinemaListByFilters(offset.value, limit.value, districtId.value, areaId.value, lineId.value, stationId.value, true, hallTypeId.value, brandId.value, serviceId.value, store.currentCity.id, store.geolocation.latitude, store.geolocation.longitude)
};

const goToCinemaDetail = (cinemaId, cinemaLocation) => {

  router.push({ path: `/cinema/${cinemaId}` })


};



</script>

<style scoped>
.line-ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
}

.line-width {
  width: 280px;
}

.cinemas-dropdown {
  position: fixed;
  /* margin-top: 50.5px; */
  top: 94.5px;
  width: 100%;
  z-index: 10;
}

.list {
  height: 100%;
  margin-top: 100px;
  padding: 10px;
  background-color: #fff;
}

.list .cinema-item {
  cursor: pointer;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.list .cinema-item:last-child {
  border: 0;
}

.list .cinema-item .services .van-tag {
  font-size: 10px;
  margin-right: 5px;
}

.list .title {
  color: #000;
  font-size: 16px;
  flex-wrap: nowrap;
}

.list .title .val-col {
  width: 200px;
}

.list .title .price {
  color: #f03d37;
}

.list .title .price span {
  font-size: 11px;
}

.list .location {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  flex-wrap: nowrap;
  width: 100%;
}

.list .location .val-col {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  width: 100%;
}

/*************************** 特色 *******************/
.special {
  padding: 10px;
  color: #777;
}

.special h5 {
  font-size: 14px;
  margin: 0 0 10px 0;
  font-weight: normal;
}

.special .special-btn {
  font-size: 10px;
  /* text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap; */
}

.van-grid {
  color: #777;
}

.van-grid-item {
  cursor: pointer;
}


/**** 选中的按钮*****/
.active-btn {
  color: #e54847 !important;
  background: #fcf0f0 !important;
  border: #f03d37 !important;
}

.reset {
  width: 80px;
  height: 36px;
  padding: 5px;
}

.confirm {
  width: 80px;
  height: 36px;
  padding: 5px;
  background-color: #e54847;
  color: #fff !important;
}
</style>
